package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.model.mongo.VideoScore;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RecommendVideoListener {

    @Autowired
    private MongoTemplate mongoTemplate;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "log.video", durable = "true"),
            exchange = @Exchange(name = "tanhua.log.exchange", type = "topic"),
            key = {"log.video"}
    ))
    public void countVideoScore(String message) {
        Map <String,String> map = JSON.parseObject(message, Map.class);
        Long userId = Long.valueOf(map.get("userId"));
        String type = map.get("type");

        VideoScore videoScore = new VideoScore();
        videoScore.setUserId(userId);
        videoScore.setScore(getScore(type));
        videoScore.setDate(System.currentTimeMillis());

        mongoTemplate.insert(videoScore);
    }

    /**
     * 得分
     * @param type
     * @return
     * 0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
     * - 发布+2
     * - 点赞 +5
     * - 评论 + 10
     */
    private double getScore(String type) {
        double score = 0d;
        switch (type) {
            case "0301" :
                score += 2d;
                break;
            case "0302":
                score += 5d;
                break;
            case "0303":
                score -= 5d;
                break;
            case "0304":
                score += 10d;
                break;
            default: break;
        }
        return score;
    }
}
